/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Model;

import Controller.LogManager;
import Controller.ProductManager;
import java.io.IOException;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author pauld
 */
@WebServlet(name = "CreateProduct", urlPatterns = {"/CreateProduct"})
public class CreateProduct extends HttpServlet {
    private static HttpSession cpSession = null;
    private static String name = null,
            synopsis = null,
            genre = null,
            type = null,
            price = null;
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        //add the product then store the result in a variable
        int result = ProductManager.addProduct(name, synopsis, genre, type, price);
        
        switch (result){
            //product was succesfully added
            case 1: 
                LogManager.logEvent("CreateProduct." + Thread.currentThread().getStackTrace()[1].getMethodName(), Level.INFO, "Add Product Successful: " + name, request.getRemoteAddr(), String.valueOf(request.getSession().getAttribute("name")));
                response.sendRedirect("admin/productPanel.jsp?status=1");
                break;
            //the product name and type already exists in the db
            case 0: 
                LogManager.logEvent("CreateProduct." + Thread.currentThread().getStackTrace()[1].getMethodName(), Level.WARNING, "Add Product Unsuccessful - Attempt To Add Existing Product: " + name, request.getRemoteAddr(), String.valueOf(request.getSession().getAttribute("name")));
                response.sendRedirect("admin/productPanel.jsp?status=-1");
                break;
            //if there was an error in the db
            case -1: 
                LogManager.logEvent("CreateProduct." + Thread.currentThread().getStackTrace()[1].getMethodName(), Level.SEVERE, "Add Product Unsuccessful - Database Error", request.getRemoteAddr(), String.valueOf(request.getSession().getAttribute("name")));
                response.sendRedirect("admin/productPanel.jsp?status=-2");
                break;
        }
    }
    
    //method for checking the user inputs
    //returns true if user inputs are valid and fals otherwise
    private static boolean checkInput(HttpServletRequest request){
        //get the form values and store them on the variables
        name = request.getParameter("name");
        synopsis = request.getParameter("synopsis");
        genre = request.getParameter("genre");
        type = request.getParameter("type");
        price = request.getParameter("price");
        
        //check the form inputs using regex
        String regexXSS = "[<(.*?)>]",    //blacklist
                regexAlpha = "^[A-Za-z/ ]+$",    //whitelist
                regexNum = "^[0-9.]+$"; //whitelist
        Pattern pXSS = Pattern.compile(regexXSS, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE),
                pAlpha = Pattern.compile(regexAlpha, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE),
                pNum = Pattern.compile(regexNum, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher mXSSName = pXSS.matcher(name),
                mGenre = pAlpha.matcher(genre),
                mType = pAlpha.matcher(type),
                mPrice = pNum.matcher(price);
        boolean resultXSSName = mXSSName.find(),
                resultPrice = mPrice.find(),
                resultGenre = mGenre.find(),
                resultType = mType.find();
        
        //check the legth of the inputs
        //checking for the regex
        if( (name.length() > 0 && name.length() <= 45) && 
                (synopsis.length() > 0 && synopsis.length() <= 512) && 
                genre.length() != 0 && 
                type.length() != 0 && 
                price.length() != 0 &&
                !resultXSSName &&
                resultPrice &&
                resultGenre &&
                resultType)
            return true;
        else
        {
            LogManager.logEvent("CreateProduct." + Thread.currentThread().getStackTrace()[1].getMethodName(), Level.WARNING, "Add Product Unsuccessful - Invalid Input", request.getRemoteAddr(), cpSession.getAttribute(name).toString());
            return false;
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        cpSession = request.getSession();
        
        //before adding product to database the inputs are checked
        if( checkInput(request) ){
            cpSession.setAttribute("product-name", "");
            cpSession.setAttribute("product-synopsis", "");
            cpSession.setAttribute("product-price", "");
            
            processRequest(request, response);
        }
        else{
            cpSession.setAttribute("product-name", name);
            cpSession.setAttribute("product-synopsis", synopsis);
            cpSession.setAttribute("product-price", price);
        
            response.sendRedirect("admin/productPanel.jsp?status=0");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        cpSession = request.getSession();
        
        //before adding product to database the inputs are checked
        if( checkInput(request) ){
            cpSession.setAttribute("product-name", "");
            cpSession.setAttribute("product-synopsis", "");
            cpSession.setAttribute("product-price", "");
            
            processRequest(request, response);
        }
        else{
            cpSession.setAttribute("product-name", name);
            cpSession.setAttribute("product-synopsis", synopsis);
            cpSession.setAttribute("product-price", price);
            
            response.sendRedirect("admin/productPanel.jsp?status=0");
        }
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
